<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" class="demo-form-inline">
      <i class="el-icon-search btn-search" @click="handleShowSearch()"></i>
      <div v-show="showbtns==true" class="search-lf">
        <el-form-item label="PO单号">
          <el-input v-model="listQuery.po" placeholder="PO单号"></el-input>
        </el-form-item>
           <el-form-item label="合同编号">
          <el-input v-model="listQuery.contractNo" placeholder="合同编号"></el-input>
        </el-form-item>
        <el-form-item width="200px" label="客户名称">
          <el-input v-model="listQuery.customerName" placeholder="客户名称"></el-input>
        </el-form-item>
        <el-form-item label="战区">
          <el-select filterable
            v-model="listQuery.regionName"
            
            clearable
            @change="handleChangePro4($event)"
            placeholder="请选择"
          >
            <el-option
              v-for="item in regiosList"
              :key="item.id"
              :label="item.region"
              :value="item.region"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省份">
          <el-select filterable v-model="listQuery.provinceName"  clearable placeholder="请选择">
            <el-option
              v-for="item in allProvinceList"
              :key="item.provinceId"
              :label="item.province"
              :value="item.province"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="PO状态">
          <el-select filterable v-model="listQuery.poState"  clearable placeholder="请选择">
            <!-- <el-option label="未启动" value="1"></el-option> -->
            <el-option label="进行中" value="2"></el-option>
            <el-option label="已交付" value="3"></el-option>
                <el-option label="已验收" value="4"></el-option>
            <el-option label="已完结" value="5"></el-option>
            <el-option label="已终止" value="6"></el-option>
            <el-option label="已过期" value="7"></el-option>

          </el-select>
        </el-form-item>
        <el-form-item style="width:100px">
          <el-button type="primary" plain @click="getList()">查询</el-button>
        </el-form-item>
      </div>

      <div class="btn-box">
        <a
          class="el-button el-button--success el-button--medium"
          href="http://123.57.59.222:8081/api/file/po_template.xlsx"
          type="primary"
        >模版下载</a>
   <el-upload
         
              :action="UploadUrl()"
             :show-file-list="false"
            
            :on-success="handleImageSuccess"
          class="upload_image"
        >
          <el-button type="primary" v-show='roleName=="admin"'>导入</el-button>
        </el-upload>
        <el-button
          :disabled="list.length<=0"
          type="primary"
          icon="el-icon-document"
          @click="po_excel"
        >导出excel</el-button>
      </div>
    </el-form>
    <el-table
      v-loading="listLoading"
      border
      :data="list"
      fit
       height='650px'
       highlight-current-row
      style="width: 100%"
    >
     
      <el-table-column align="center" width='60px'  label="序号">
        <template slot-scope="scope">
          <span>{{scope.$index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="130px" label="PO单号">
        <template slot-scope="{row}">
          <router-link :to="'/po_detail?id='+row.id+'&po='+row.po" class="link-type">
            <span>{{ row.po }}</span>
          </router-link>
        </template>
      </el-table-column>

      <el-table-column align="center" width="200px" label="产品类型">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-select filterable
              v-model="poesList.productTypeName"
              @change="handleChangePro($event)"
              placeholder="请选择产品类型"
            >
              <el-option
                v-for="item in productTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </template>
          <span v-else>{{ row.productTypeName }}</span>
        </template>
      </el-table-column>

      <el-table-column sort align="center" width="100px" label="创建时间">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
             <el-date-picker
            v-model="poesList.createTime"
            type="date"
            placeholder="选择日期"
            format="yyyy/MM/dd"
            value-format="yyyy/MM/dd"
          ></el-date-picker>
          </template>
          <span v-else>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="战区">
        <template slot-scope="{row}">
         <template v-if="row.rowEdit">
             <el-select filterable v-model="poesList.regionName"  @change="handleChangePro4($event)" placeholder="请选择">
              <el-option
                v-for="item in regiosList"
                :key="item.id"
                :label="item.region"
                :value="item.region"
              ></el-option>
            </el-select>
          </template>
          <span v-else>{{ row.regionName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="省份">
        <template slot-scope="{row}">
         <template v-if="row.rowEdit">
           <el-select filterable v-model="poesList.provinceName" @change="handleChangePro3($event)" placeholder="请选择">
              <el-option
                v-for="item in provinceList"
               :key="item.provinceId"
              :label="item.provinceName"
              :value="item.provinceName"
              ></el-option>
            </el-select>
          </template>
          <span v-else>{{ row.provinceName }}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" label="成功部门">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-select
                filterable
                v-model="poesList.teamId"
                  @change="handleChangePro5($event)"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in teamNameList"
                  :key="item.id"
                  :label="item.teamName"
                  :value="item.id"
                ></el-option>
              </el-select>
          </template>
          <span v-else>{{ row.teamName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="180px" label="合同编号">
        <template slot-scope="{row}">
            <template v-if="row.rowEdit">
            <el-input v-model="poesList.contractNo"/>
          </template>
          <span v-else>{{ row.contractNo }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="200px" label="客户名称">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-input v-model="poesList.customerName"/>
          </template>
          <span v-else>{{ row.customerName }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" width='110px' label="合同金额">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-input type='number' v-model="poesList.contractAmount"/>
          </template>
          <span v-else>{{ row.contractAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="合同申请人">
        <template slot-scope="{row}">
          <span>{{ row.contractApplicant }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120px" label="合同交付时间">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-date-picker
              v-model=" poesList.contractDeliveryDate"
              type="date"
              placeholder="选择日期"
              format="yyyy/MM/dd"
              value-format="yyyy/MM/dd"
            ></el-date-picker>
          </template>
          <span v-else>{{ row.contractDeliveryDate }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" width="170px" label="合同总时长（分钟）">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-input  type='number' v-model="poesList.contractTotalTimeLength"></el-input>
          </template>
          <span v-else>{{ row.contractTotalTimeLength }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="170px" label="已完成时长（分钟）">
        <template slot-scope="{row}">
          <span>{{ row. contractFinishedTimeLength }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="170px" label="未完成时长（分钟）">
        <template slot-scope="{row}">
          <span>{{ row.contractUnfinishedTimeLength }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="已回款">
        <template slot-scope="{row}">
         <template v-if="row.rowEdit">
            <el-input v-model="poesList.contractPaymentReceived"/>
          </template>
          <span v-else>{{ row.contractPaymentReceived }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="未回款">
        <template slot-scope="{row}">
           <template v-if="row.rowEdit">
            <el-input v-model="poesList.contractOutstandingPayment"/>
          </template>
          <span v-else>{{ row.contractOutstandingPayment }}</span>
        </template>
      </el-table-column>
   <el-table-column align="center" label="更新时间">
        <template slot-scope="{row}">
           <template v-if="row.rowEdit">
            <!-- <el-input v-model="poesList.updateTime"/> -->
            
             <el-date-picker
      v-model="poesList.updateTime"
      format="yyyy/MM/dd"
      size='mini'
      type="date"
      value-format="yyyy/MM/dd"
      placeholder="选择日期">
    </el-date-picker>
          </template>
          <span v-else>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="版权归属">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-input v-model=" poesList.copyrightOwnership"></el-input>
          </template>
          <span v-else>{{ row.copyrightOwnership }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="版权费">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-input v-model=" poesList.copyrightFee"></el-input>
          </template>
          <span v-else>{{ row.copyrightFee }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商务杂费">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-input v-model=" poesList.businessSundryFee"></el-input>
          </template>
          <span v-else>{{ row.businessSundryFee }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" width="100px" label="第三方采购">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-input v-model=" poesList.contractPurchaseAmount"></el-input>
          </template>
          <span v-else>{{ row.contractPurchaseAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="合同毛利">
        <template slot-scope="{row}">
           <template v-if="row.rowEdit">
            <el-input v-model="poesList.contractGrossProfit"/>
          </template>
          <span v-else>{{ row.contractGrossProfit }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" width="100px" label="预测毛利率">
        <template slot-scope="{row}">
            <template v-if="row.rowEdit">
            <el-input v-model="poesList.forecastGrossProfitRate"/>
          </template>
          <span v-else>{{ row.forecastGrossProfitRate }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" width="120px" label="预估生产成本">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-input v-model=" poesList.estimatedGenerationCost"></el-input>
          </template>
          <span v-else>{{ row.estimatedGenerationCost }}</span>
        </template>
      </el-table-column>
        <el-table-column align="center" label="已支付">
        <template slot-scope="{ row }">
          <span>{{ row.paidAmountSum }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="未支付">
        <template slot-scope="{ row }">
          <span>{{ row.unpaidAmountSum }}</span>
        </template>
      </el-table-column>
        <el-table-column class-name="status-col" label="预估金额">
        <template slot-scope="{ row }">
          <span>{{ row.estimatedGenerationCostSum }}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" width="100px" label="风险计提">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-input v-model="poesList.riskProvision" />
          </template>
          <span v-else>{{ row.riskProvision }}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" width="100px" label="风险利率">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-input v-model="poesList.riskRate" />
          </template>
          <span v-else>{{ row.riskRate }}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" width="100px" label="渠道费用">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-input v-model="poesList.channelFee" />
          </template>
          <span v-else>{{ row.channelFee }}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" width="100px" label="产学合作费">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-input v-model="poesList.industryAndUniversityCooperationFee" />
          </template>
          <span v-else>{{ row.industryAndUniversityCooperationFee }}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" width="100px" label="其他">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-input v-model="poesList.other" />
          </template>
          <span v-else>{{ row.other }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="PO状态">
        <template slot-scope="{row}">
          <!-- <span>{{ row.state   }}</span> -->
          <el-tag :type="row.poState | statusColorFilter">{{ row.poState | statusFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120px" label="约定售后期限">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-date-picker
              v-model="poesList.afterSalePeriod"
              type="date"
              placeholder="选择日期"
              format="yyyy/MM/dd"
              value-format="yyyy/MM/dd"
            ></el-date-picker>
          </template>
          <span v-else>{{ row.afterSalePeriod }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120px" label="po备注">
        <template slot-scope="{row}">
          <template v-if="row.rowEdit">
            <el-input v-model="poesList.poRemark"></el-input>
          </template>
          <span v-else>{{ row.poRemark }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="150">
        <template slot-scope="{row}">
          <el-button
            v-if="row.rowEdit"
            type="success"
            size="mini"
            icon="el-icon-circle-check-outline"
            @click="confirmRole(row)"
          >保存</el-button>
          <el-button
            v-else
            type="primary"
            @click="handleEdit(row)"
            size="mini"
            :disabled="editDisabled==true"
            icon="el-icon-edit"
          >编辑</el-button>

          <el-button
            @click="handleDel(row.id)"
            class="mg-l"
            type="danger"
            size="mini"
            icon="el-icon-delete"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>11"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  infoPos,
  posList,
  contractsList,
  updatePos,
  addContract,
  updateContracts,
  getProvinces,
  delPos,
} from "@/api/supplier";
import { getProductType, getContractType, baseUrl2 } from "@/api/remote-search";
import { Message } from "element-ui";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { regiosList } from "@/api/user";
import { RegionsProvince,getteamNamesAll } from "@/api/region";
import {exportPo} from '@/api/exportExcel'
export default {
  name: "posList",
  components: { Pagination },
  filters: {
    statusColorFilter(status) {
      const statusMap = {
        1: "success",
        2: "warning",
        3: "#E6A23C",
        4: "info",
        5: "#AB6666",
        6: "#AB6666",
        7: "danger",
      };
      return statusMap[status];
    },
    statusFilter(status) {
      const statusMap = {
        1: "未启动",
        2: "进行中",
        3: "已交付",
        4: "已验收",
        5: "已完结",
        6: "已终止",
        7: "已过期",
      };
      //  <!-- <el-option label="未启动" value="1"></el-option> -->
      //       <el-option label="进行中" value="2"></el-option>
      //       <el-option label="已交付" value="3"></el-option>
      //           <el-option label="已验收" value="4"></el-option>
      //       <el-option label="已完结" value="5"></el-option>
      //       <el-option label="已终止" value="6"></el-option>
      //       <el-option label="已过期" value="7"></el-option>
      return statusMap[status];
    },
  },
  data() {
    return {
      showbtns: false,
      list: [],
      editDisabled: false,
      roleName:sessionStorage.getItem('memberName'),
      downloadLoading: false,
      poesList: {
        rowEdit: false,
      },
      provinceList: [], //战区下面省份
      allProvinceList:[],//所有省份
      regiosList: [], //战区
      downloadLoading: false,
      total: 0,
      dialogVisibleMenu: false,
      listLoading: true,
      productTypeList: [], //产品类型
      listQuery: {
        access_token: sessionStorage.getItem("token"),
        page: 1,

        customerName: "",
        contractNo: "",
        regionName: "",
        provinceName: "",
        po: "",
        poState: "",
        pageSize: 20,
      },

      userId: "", //用户id
      rolesList: [],

      dialogVisible: false,
      dialogType: "new",
      checkStrictly: false,

      ids: "",
      teamNameList:[],
    };
  },
  created() {
    this.getList();
    this.getListes();
  },
  computed: {},
 methods: {
     UploadUrl(){
      return baseUrl2+'/api/file/import_po'
    },
      handleClose(){
      this.editDisabled = false;
    },
    handleShowSearch() {
      this.showbtns = !this.showbtns;
    },
    po_excel() {
      exportPo(this.listQuery)
      // window.location.href =
      //   baseUrl2 +
      //   "/api/file/export_po?po=" +
      //   this.listQuery.po +
      //   "&customerName=" +
      //   this.listQuery.customerName +
      //   "&contractNo=" +
      //   this.listQuery.contractNo +
      //   "&regionName=" +
      //   this.listQuery.regionName +
      //   "&provinceName=" +
      //   this.listQuery.provinceName +
      //   "&poState=" +
      //   this.listQuery.poState;
    },
    handleImageSuccess(file) {
      if (file.code == 200) {
        this.$message.success(file.message);
        this.getList();
      } else {
        this.$message.error(file.message);
      }
    },
    handleChangePro4(id) {
      let obj = {};
      obj = this.regiosList.find((item) => {
        return item.region === id;
      });
      this.poesList.provinceName='';
      this.poesList.regionId=obj.id;
    
      RegionsProvince(obj.id).then((res) => {
        this.provinceList = res.data.data;
      });
    },
        handleChangePro5(id) {
        console.log(id)
      let obj = {};
      obj = this.teamNameList.find((item) => {
        return item.id === id;
      });
      this.poesList.teamName = obj.teamName;
    },
      handleChangePro3(id) {
     let obj = {};
      obj = this.provinceList.find((item) => {
         
        return item.provinceName === id;  
      });
     this.poesList.provinceId = obj.provinceId;
      console.log(this.poesList)
    
    },
    getListes() {
        getteamNamesAll().then(res=>{
         this.teamNameList=res.data.data
      })
       getProvinces().then((res) => {
        this.allProvinceList = res.data.data;
      });
      regiosList().then((res) => {
        this.regiosList = res.data.data;
      });
      getProductType().then((res) => {
        this.productTypeList = res.data.data;
      });
    },
    handleChangePro(id) {
      let obj = {};
      obj = this.productTypeList.find((item) => {
        return item.name === id;
      });
      console.log(obj);
      this.poesList.productTypeId = obj.id;
    },
    handleDetail(row) {
      console.log(row.id);
      this.$router.push({ path: "/po_detail", query: { id: row.id } });
    },
       getList() {
       
       this.editDisabled = false;
      this.listLoading = true;
      posList(this.listQuery)
        .then((response) => {
          this.$nextTick(()=>{
            this.list = response.data.data.rows;
          this.total = response.data.data.total;
          this.listLoading = false;
          })
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    handleDel(id) {
      this.$confirm("确定删除该数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          delPos(id).then((res) => {
            if (res.data.code == "200") {
              this.$message.success(res.data.message);
              this.getList();
            } else {
              this.$message.error(res.data.message);
            }
          });
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    handlenewContract() {
      this.dialogType = "new";
      this.dialogVisible = true;
      // this.poesList='';
    },
    handleEdit(row) {
      this.editDisabled = true;
      this.dialogType = "edit";
      // this.dialogVisible = true;
      row.rowEdit = !row.rowEdit;
      //  console.log(row.rowEdit)
      this.poesList = row;
      this.poesList.id = row.id;
      //   this.poesList.rowEdit=false;
    },
    confirmRole(row, id) {
      const isEdit = this.dialogType === "edit";
      if (isEdit) {
        // this.poesList.rowEdit = false;
        updatePos(this.poesList).then((res) => {
          if (res.data.code == "200") {
            this.$message.success(res.data.message);
            // this.dialogVisible = false;
            row.rowEdit = false;

            this.getList();
            this.editDisabled = false;
          } else {
            this.$message.error(res.data.message);
          }
        });
        return false;
      }
      // this.poesList.id=12;
      // this.poesList.rowEdit=false;
      //       updatePos(this.poesList).then((res) => {
      //         console.log(res);
      //         if ((res.code = "200")) {
      //           this.$message.success(res.data.message);

      //           this.dialogVisible = false;
      //           this.posList = "";
      //           this.getList();
      //         }
      //       });
    },
  },
};
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
